﻿using System;
using System.Linq;
using Autofac;
using MediatR;

namespace EventBus
{
    /// <summary>
    ///
    /// </summary>
    public class MediatorModule : Module
    {
        /// <summary>
        ///
        /// </summary>
        /// <param name="builder"></param>
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<Mediator>()
                .As<IMediator>()
                .InstancePerLifetimeScope().PropertiesAutowired();

            builder.RegisterType<EventBusMemoryBus>()
                .As<IEventBus>()
                .InstancePerLifetimeScope().PropertiesAutowired();

            var mediatorOpenTypes = new[]
            {
                typeof(IRequestHandler<,>),
                typeof(IRequestHandler<>),
                typeof(INotificationHandler<>),
            };

            var assemblies = AppDomain.CurrentDomain.GetAssemblies()
                .ToArray();

            foreach (var type in mediatorOpenTypes)
            {
                builder
                    .RegisterAssemblyTypes(assemblies)
                    .AsClosedTypesOf(type)
                    .AsImplementedInterfaces()
                    .PropertiesAutowired();
            }

            builder.Register<ServiceFactory>(context =>
            {
                var componentContext = context.Resolve<IComponentContext>();
                return t => componentContext.TryResolve(t, out var o) ? o : null;
            });
        }
    }
}
